var $ = exports
var arrayUtils = require("arrayUtils")
var tags = require("./html4Tags").tagsWithType

$.render = function(rosa) {return "<!DOCTYPE html>\n" + $.renderPart(rosa)}

var sanitizeAttrKey = function(key) { 
	return ("" + key).replace(/[\'\"=]/g,"") 
}

var sanitizeAttrValue = function(value) { 
	return ("" + value).replace(/[\'\"]/g,"") 
}

var sanitizeText = function(text) {
	return ("" + text).replace(/&/g,"&amp;").replace(/</g,"&lt;")
}

var renderAttr = function(key, value) {
	return " " + sanitizeAttrKey(key) + '="' + sanitizeAttrValue(value) + '"'
}

var renderAttrs = function(attrs) {
	var rv = ""
	for (var i in attrs) {
		rv += renderAttr(i,attrs[i])
	}
	return rv
}

var renderArray = function(ary) {
	return ary.map(function(m){return $.renderPart(m)}).join("")
}

var renderTag = function(tag) {
	return "<" + tag.name + renderAttrs(tag.attrs) + ">" + (
		tags[tag.name] === "simple" ?
			"" :
			renderArray(tag.elems || []) + "</" + tag.name + ">"
	)
}

$.renderPart = function(rosa){
	if (arrayUtils.isArray(rosa)) {return renderArray(rosa)}
	if (rosa.isTag) {return renderTag(rosa)}
	if (rosa.isEscaped) {return rosa.text}
	return sanitizeText(rosa)
}